<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container>
      <a-form-model ref="form" :form="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="申请组织类型" prop="applyOrgCategory" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!-- <a-input disabled v-decorator="['materialName', validatorRules.materialName]" placeholder="请输入物品名称"></a-input> -->
              <a-select
                :disabled="!editable || editableFiexd['applyOrgCategory']"
                placeholder="请选择组织类型"
                v-model="model.applyOrgCategory"
                @change="setApplyOrgCategory"
              >
                <a-select-option value="depart">直属部门</a-select-option>
                <a-select-option value="society">社团</a-select-option>
                <a-select-option value="stdGroup">学生组织</a-select-option>
                <a-select-option value="volunteerTeam">志愿者队伍</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="申请组织" prop="applyOrgId" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <XSelectOrganization
                ref="XSelectOrganization"
                v-model="model.applyOrgId"
                :text="model.applyOrgName"
                :searchType="model.applyOrgCategory"
                :disabled="!editable || editableFiexd['applyOrgId']"
                @onSelected="setApplyOrgName"
              ></XSelectOrganization>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <label style="margin-left:50px;">负责人</label>
            <a-form-model-item label="老师" prop="instructorId" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <x-select-user-by-dep
                v-model="model.instructorId"
                @selected="setInstructor"
                :disabled="!editable || editableFiexd['instructorId']"
                :multi="false"
                userType="teacher"
              ></x-select-user-by-dep>
            </a-form-model-item>

            <a-form-model-item label="老师电话" prop="instructorPhone" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                v-model="model.instructorPhone"
                :disabled="!editable || editableFiexd['instructorPhone']"
                placeholder="请输入老师电话"
              ></a-input>
            </a-form-model-item>

            <a-form-model-item label="学生" prop="applierId" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <x-select-user-by-dep
                v-model="model.applierId"
                @selected="setUser"
                :disabled="!editable || editableFiexd['applierId']"
                :multi="false"
              ></x-select-user-by-dep>
            </a-form-model-item>

            <a-form-model-item label="学生电话" prop="studentPhone" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input
                v-model="model.studentPhone"
                :disabled="!editable || editableFiexd['studentPhone']"
                placeholder="请输入学生电话"
              ></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="场地物资" prop="details" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <MaterialPick
                v-model="model.details"
                :disabled="!editable || editableFiexd['details']"
              ></MaterialPick>
            </a-form-model-item>
          </a-col>

          <!-- <a-col :span="24">
            <a-form-model-item label="物资" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <MaterialPick searchType="WZ" v-decorator="['style', validatorRules.style]"></MaterialPick>
            </a-form-model-item>
          </a-col> -->

          <a-col :span="24">
            <label style="margin-left:50px;">活动内容</label>
            <a-form-model-item label="活动主题" prop="theme" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="model.theme" :disabled="!editable || editableFiexd['theme']" placeholder="请输入活动主题"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="活动形式" prop="style" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="model.style" :disabled="!editable || editableFiexd['style']" placeholder="请输入活动形式"></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item :labelCol="labelCol" prop="meetingDate" :wrapperCol="wrapperCol" label="活动日期">
              <j-date placeholder="请选择活动日期" class="query-group-cust" v-model="model.meetingDate" 
                :disabled="!editable || editableFiexd['meetingDate']"></j-date>
            </a-form-model-item>
          </a-col>

          <!-- 理由 -->
          <a-col :span="24">
            <a-form-model-item prop="reason" label="申请理由" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea rows="4" v-model="model.reason" :disabled="!editable || editableFiexd['reason']"/>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item prop="timeRange" :labelCol="labelCol" :wrapperCol="wrapperCol" label="使用时间">
              <a-range-picker
                showTime
                format="YYYY-MM-DD HH点"
                :placeholder="['开始时间', '结束时间']"
                :disabled="!editable || editableFiexd['timeRange']"
                v-model="model.timeRange"
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="24" v-show="returnTimeEditable">
            <a-form-model-item prop="returnTime" :labelCol="labelCol" :wrapperCol="wrapperCol" label="归还时间时间">
              <j-date placeholder="请选择归还时间时间" format="YYYY-MM-DD HH:mm:ss" class="query-group-cust" :disabled="!editable || editableFiexd['returnTime']" v-model="model.returnTime"></j-date>
            </a-form-model-item>
          </a-col>

        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import moment from 'moment'
import { merge, pick } from 'lodash'
import JFormContainer from '@/components/jeecg/JFormContainer'
import JDate from '@/components/jeecg/JDate'
import JSelectMultiple from '@/components/jeecg/JSelectMultiple'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import XSearchUser from '@/components/extends/XSearchUser'
import XSelectUserByDep from '@/components/extends/XSelectUserByDep'
import XSelectOrganization from '@/components/extends/XSelectOrganization'
import MaterialPick from './MaterialPick'
export default {
  name: 'MaterialApplyForm',
  components: {
    MaterialPick,
    JFormContainer,
    JDate,
    JSelectMultiple,
    JDictSelectTag,
    JSelectDepart,
    XSearchUser,
    XSelectUserByDep,
    XSelectOrganization
  },
  model: {
    prop: 'data',
    event: 'onchange'
  },
  props: {
    dataId: String,
    data: {
      type: Object,
      default: () => {
        return {}
      }
    },
    returnTimeEditable: Boolean,
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    editable: {
      type: Boolean,
      default: true
    },
    editableFiexd: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      loading:false,
      userDisabled: false,
      form: this.$form.createForm(this),
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        applyOrgId:[{ required: true, message: '请选择主办单位！' , trigger: 'change'}],
        applyOrgCategory:[{ required: true, message: '请选择单位类型！' , trigger: 'change'}],
        theme: [{ required: true, message: '请输入活动主题!' , trigger: 'change'}],
        style: [{ required: true, message: '请输入活动形式!' , trigger: 'change'}],
        instructorId: [{ required: true, message: '请选择指导老师!' , trigger: 'change'}],
        instructorPhone: [{ required: true, message: '请输入手机号码!' , trigger: 'change'}, { validator: this.validateMobile , trigger: 'blur'}],
        applierId: [{ required: true, message: '请选择申请人!' }],
        studentPhone: [{ required: true, message: '请输入学生联系电话!' , trigger: 'change'}, { validator: this.validateMobile , trigger: 'blur'}],
        code: [{ required: true, message: '请输入物品编码!' }],
        details: [{ required: true, message: '请选择场地和物资!' , trigger: 'change'}],
        type:[{ required: true, message: '请选择类型！' , trigger: 'change'}],
        reason: [{ required: true, message: '请填写理由！' , trigger: 'change'}],
        meetingDate:[{ required: true, message: '请选择活动日期！' , trigger: 'change'}],
        timeRange:[{ required: true, message: '请选择使用时间！' , trigger: 'change'}],
        count: [{ required: true, message: '请输入物品数量！' , trigger: 'change'}]
      },
      url: {
        add: '/materialApply/add',
        edit: '/materialApply/edit',
        queryById: '/materialApply/queryById'
      }
    }
  },
  computed: {

  },
  watch: {
    dataId(nv, on) {
      if (nv) {
        this.getData(nv)
      }
    },
    data: {
      handler(nv, ov) {
        this.model = merge(this.model, nv)
      },
      immediate: true,
      deep: true
    },
    model: {
      handler(nv, ov) {
        this.$emit('onchange', nv)
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    if (this.dataId) {
      this.getData(this.dataId)
    }
  },
  methods: {
    add() {
      this.userDisabled = false
      this.open({})
    },
    apply(record) {
      this.userDisabled = true
      this.open({
        workflowModel: {
          operation: 'start'
        },
        ...record
      })
    },
    edit(record) {
      this.userDisabled = true
      this.open(record)
    },
    open(record) {
      merge(this.model,record,{})
      this.$set(this.model,'timeRange',[
        record.startTime ? moment(record.startTime) : null,
        record.endTime ? moment(record.endTime) : null
      ])
      if (this.model.id) {
        this.getData(record.id)
      }
    },
    validateMobile(rule, value, callback) {
      if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)) {
        callback()
      } else {
        callback('电话号码格式不正确!')
      }
    },
    setInstructor(data) {
      let rows = data.rows
      if (Array.isArray(rows) && rows[0]) {
        if(this.model.instructorId!=data.value){
          this.$set(this.model,'instructor',rows[0].realname)
          this.$set(this.model,'instructorPhone',rows[0].phone)
        }else{
          !this.model.instructorPhone&&this.$set(this.model,'instructorPhone',rows[0].phone)
        }
      }
    },
    setUser(data) {
      let rows = data.rows
      if (Array.isArray(rows) && rows[0]) {
        if(this.model.instructorId!=data.value){
          this.$set(this.model,'student',rows[0].realname)
          this.$set(this.model,'studentPhone',rows[0].phone)
        }else{
          !this.model.studentPhone&&this.$set(this.model,'studentPhone',rows[0].phone)
        }
      }
    },
    setApplyOrgCategory(data) {
      this.$set(this.model,'applyOrgCategory',data)
      this.$set(this.model,'applyOrgId','')
      this.$set(this.model,'applyOrgName','')
      this.$refs.XSelectOrganization.names = ''
    },
    setApplyOrgName(data) {
      if (Array.isArray(data) && data[0]) {
        this.$set(this.model,'applyOrgName',data[0].name)
      }
    },
    getData(id) {
      this.loading = true
      getAction(this.url.queryById, { id })
        .then(res => {
          this.loading = false
          this.model = Object.assign({},this.model,res.result)
          this.$set(this.model,'timeRange',[
            this.model.startTime ? moment(this.model.startTime) : null,
            this.model.endTime ? moment(this.model.endTime) : null
          ])
        })
        .finally(() => {
          this.loading = false
        })
    },
    submitForm() {
      const that = this
      return new Promise(function(resolve, reject) {
        // 触发表单验证
        that.$refs.form.validate((valid, Field) => {
          if (valid) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!that.model.id) {
              httpurl += that.url.add
              method = 'post'
            } else {
              httpurl += that.url.add
              method = 'post'
            }
            const formData = Object.assign({}, that.model)
            formData.startTime = formData.timeRange[0].format('YYYY-MM-DD HH:mm:ss')
            formData.endTime = formData.timeRange[1].format('YYYY-MM-DD HH:mm:ss')
            delete formData.timeRange
            formData.details = formData.details.map(item => {
              return {
                applyId: formData.id,
                ...item
              }
            })
            httpAction(httpurl, formData, method)
              .then(res => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                  resolve(res)
                } else {
                  that.$message.warning(res.message)
                  reject()
                }
              })
              .finally(() => {
                that.confirmLoading = false
              })
          } else {
            that.$message.warning('校验失败，请检查表单内容！')
            reject(Field)
          }
        })
      })
    }
  }
}
</script>
